package com.example.stella.activities;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.stella.R;
import com.example.stella.adapters.CategoryAdapter;
import com.example.stella.database.CategoryDAO;
import com.example.stella.database.TransactionDAO;
import com.example.stella.models.Category;
import com.example.stella.models.Transaction;
import com.example.stella.utils.SessionManager;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * 添加交易记录Activity - 支持添加收入和支出记录
 */
public class AddTransactionActivity extends AppCompatActivity {
    private Button btnBack, btnSave, btnIncomeType, btnExpenseType;
    private EditText etAmount, etDescription;
    private TextView tvDate;
    private RecyclerView rvCategories;
    private CategoryAdapter categoryAdapter;
    private TransactionDAO transactionDAO;
    private CategoryDAO categoryDAO;
    private SessionManager sessionManager;
    private String selectedType = "支出"; // 默认选择支出
    private String selectedCategory = "";
    private long selectedDate;
    private SimpleDateFormat dateFormat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_transaction);

        initViews();
        initData();
        setupListeners();
    }

    /**
     * 初始化界面控件
     */
    private void initViews() {
        btnBack = findViewById(R.id.btnBack);
        btnSave = findViewById(R.id.btnSave);
        btnIncomeType = findViewById(R.id.btnIncomeType);
        btnExpenseType = findViewById(R.id.btnExpenseType);
        etAmount = findViewById(R.id.etAmount);
        etDescription = findViewById(R.id.etDescription);
        tvDate = findViewById(R.id.tvDate);
        rvCategories = findViewById(R.id.rvCategories);
    }

    /**
     * 初始化数据和设置默认值
     */
    private void initData() {
        transactionDAO = new TransactionDAO(this);
        categoryDAO = new CategoryDAO(this);
        sessionManager = new SessionManager(this);
        dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());

        // 从Intent获取交易类型
        String type = getIntent().getStringExtra("type");
        if (type != null) {
            selectedType = type;
        }

        updateTypeButtons();
        setCurrentDate();
        setupCategoryRecyclerView();
        loadCategories();
    }

    /**
     * 设置各种点击事件监听器
     */
    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());
        btnSave.setOnClickListener(v -> saveTransaction());
        btnIncomeType.setOnClickListener(v -> selectType("收入"));
        btnExpenseType.setOnClickListener(v -> selectType("支出"));
        tvDate.setOnClickListener(v -> showDatePicker());
    }

    /**
     * 更新收入/支出按钮的选中状态
     */
    private void updateTypeButtons() {
        btnIncomeType.setSelected(selectedType.equals("收入"));
        btnExpenseType.setSelected(selectedType.equals("支出"));
    }

    /**
     * 选择交易类型并重新加载对应分类
     */
    private void selectType(String type) {
        selectedType = type;
        updateTypeButtons();
        loadCategories(); // 重新加载对应类型的分类
        selectedCategory = ""; // 重置已选分类
    }

    /**
     * 设置当前日期为默认日期
     */
    private void setCurrentDate() {
        selectedDate = System.currentTimeMillis();
        tvDate.setText(dateFormat.format(selectedDate));
    }

    /**
     * 显示日期选择器
     */
    private void showDatePicker() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(selectedDate);

        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    Calendar newDate = Calendar.getInstance();
                    newDate.set(year, month, dayOfMonth);
                    selectedDate = newDate.getTimeInMillis();
                    tvDate.setText(dateFormat.format(selectedDate));
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        datePickerDialog.show();
    }

    /**
     * 设置分类选择的RecyclerView
     */
    private void setupCategoryRecyclerView() {
        rvCategories.setLayoutManager(new GridLayoutManager(this, 4)); // 4列网格布局
        categoryAdapter = new CategoryAdapter(this, category -> {
            selectedCategory = category.getName();
            categoryAdapter.setSelectedCategory(category.getName());
        });
        rvCategories.setAdapter(categoryAdapter);
    }

    /**
     * 根据当前选择的类型加载分类列表
     */
    private void loadCategories() {
        List<Category> categories = categoryDAO.getCategoriesByType(selectedType);
        categoryAdapter.setCategories(categories);
    }

    /**
     * 验证输入并保存交易记录
     */
    private void saveTransaction() {
        String amountStr = etAmount.getText().toString().trim();
        String description = etDescription.getText().toString().trim();

        // 验证金额输入
        if (amountStr.isEmpty()) {
            Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
            return;
        }

        // 验证分类选择
        if (selectedCategory.isEmpty()) {
            Toast.makeText(this, "请选择分类", Toast.LENGTH_SHORT).show();
            return;
        }

        double amount;
        try {
            amount = Double.parseDouble(amountStr);
            if (amount <= 0) {
                Toast.makeText(this, "金额必须大于0", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的金额", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建并保存交易记录
        Transaction transaction = new Transaction(
                sessionManager.getUserId(),
                selectedType,
                amount,
                selectedCategory,
                description,
                selectedDate
        );

        long result = transactionDAO.insertTransaction(transaction);
        if (result > 0) {
            Toast.makeText(this, "记录保存成功", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        }
    }
} 